﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using System.Windows;
using System.Xml;
using System.IO;
using System.Reflection;
using System.Threading;

namespace danikla
{
    public partial class dlgDanikla : Form
    {
        string filePath = "customers.xml";
        DataSet dsCustomers = new DataSet("customer");
        
        public static string DATADIR = "documents";
        public static string DIR_DELIMITER = "\\";
        public static DataGridView dgCustomers;
        public static ToolStripMenuItem mSave;
        public static Form dlgD;

        public static bool saved = true;
        
        public dlgDanikla()
        {
            InitializeComponent();
            mkDir(DATADIR);
        }

        private void Danikla_Load(object sender, EventArgs e)
        {
            if (File.Exists(filePath))
            {
                dsCustomers.ReadXml(filePath);
            }
            else
            {
                dsCustomers.Tables.Add(new DataTable("customer"));
            }

            //Verify that a Customer exists in the DataSet
            //if not, create an empty row
            if(!dsCustomers.GetXmlSchema().Contains("customer"))
            {
                DataTable t = new DataTable();
                t.TableName = "customer";
                t.Columns.Add("name");
                t.Columns.Add("phone");
                t.Columns.Add("documents");
                dsCustomers.Tables.Add(t);
            }

            //Verify that DataSet columns are valid
            DataColumn c;
            if (!dsCustomers.Tables[0].Columns.Contains("name"))
            {
                c = new DataColumn("name");
                dsCustomers.Tables[0].Columns.Add(c);
                c.SetOrdinal(0);
            }
            if (!dsCustomers.Tables[0].Columns.Contains("phone"))
            {
                c = new DataColumn("phone");
                dsCustomers.Tables[0].Columns.Add(c);
                c.SetOrdinal(1);
            }
            if (!dsCustomers.Tables[0].Columns.Contains("documents"))
            {
                c = new DataColumn("documents");
                dsCustomers.Tables[0].Columns.Add(c);
                c.SetOrdinal(2);
            }

            dataGrid.DataSource = dsCustomers;
            dataGrid.DataMember = "customer";
            
            dataGrid.Columns[0].Width = 200;
            dataGrid.Columns[0].HeaderText = "Naziv";
            dataGrid.Columns[1].HeaderText = "Telefon";
            dataGrid.Columns[2].HeaderText = "Dokumenta";

            dgCustomers = dataGrid;
            mSave = menuSave;
            dlgD = this;
        }

        private void menuSave_Click(object sender, EventArgs e)
        {
            menuSave.Enabled = false;
            dsCustomers.WriteXml(filePath, XmlWriteMode.IgnoreSchema);
            
            statusMessage("Izmene su uspešno sačuvane.", "ok");
            saved = true;
            Text = Regex.Replace(Text, @"\s*\*$", "");
        }
        public void statusMessage(string message, string className="info")
        {
            switch (className)
            {
                case "error":
                    lblMessage.BackColor = System.Drawing.Color.Red;
                    lblMessage.ForeColor = System.Drawing.Color.White;
                    break;
                case "ok":
                    lblMessage.BackColor = System.Drawing.Color.DarkGreen;
                    lblMessage.ForeColor = System.Drawing.Color.White;
                    break;
                default:
                    lblMessage.BackColor = System.Drawing.SystemColors.Info;
                    lblMessage.ForeColor = System.Drawing.SystemColors.InfoText;
                    break;
            }
            lblMessage.Text = message;
            lblMessage.Visible = true;
        }

        private void menuDocuments_Click(object sender, EventArgs e)
        {
            if (dataGrid.SelectedCells.Count > 0)
            {
                int index = dataGrid.SelectedCells[0].RowIndex;
                if (index < (dataGrid.Rows.Count -1))
                {
                    DataGridViewRow row = dataGrid.Rows[index];
                    string name = row.Cells[0].Value.ToString();

                    if (name.Length > 0)
                    {
                        Customer c = new Customer();
                        c.row = row;
                        c.Text = name;
                        c.ShowDialog();
                    }
                }
            }
        }

        private void dataGrid_CellEnter(object sender, DataGridViewCellEventArgs e)
        {
            menuDocuments.Enabled = !dataGrid.CurrentCell.OwningRow.IsNewRow;
            menuDelete.Enabled = !dataGrid.CurrentCell.OwningRow.IsNewRow;
        }

        private void menuSearch_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                search();
            }
        }

        private void search()
        {
            string kw = menuSearch.Text.ToString();
            bool found = false;
            int foundIndex = -1;
            bool findAll = false;

            if (kw.Length == 0)
            {
                findAll = true;
            }
            
            dataGrid.CurrentCell = null;

            for (int i = 0; i < dataGrid.RowCount; i++)
            {
                if (!dataGrid.Rows[i].IsNewRow)
                {
                    found = false;
                    for (int j = 0; j < dataGrid.Rows[i].Cells.Count; j++)
                    {

                        if(findAll || dataGrid.Rows[i].Cells[j].Value.ToString().ToLower().Contains(kw.ToLower()))
                        {
                            foundIndex = i;
                            found = true;
                            break;
                        }
                    }
                    dataGrid.Rows[i].Visible = found;
                }
            }
            if(dataGrid.Rows.Count > 0 && foundIndex >= 0)
            {
                dataGrid.CurrentCell = dataGrid.Rows[foundIndex].Cells[0];
            }
        }
        
        public static string toDir(string dirname)
        {
            return Regex.Replace(Regex.Replace(Regex.Replace(dirname, @"[^a-zA-Z]", "_"), @"^_+|_+$", ""), @"_+", "_");
        }

        public static void mkDir(string dirname)
        {
            if (!Directory.Exists(dirname))
            {
                Directory.CreateDirectory(dirname);
            }
        }
        public static void rmDir(string dirname, bool empty=false)
        {
            if(empty)
            {
                IEnumerable<string> files = Directory.EnumerateFiles(dirname);
                for (int i = 0; i < files.Count(); i++)
                {
                    File.Delete(dirname + DIR_DELIMITER + files.ElementAt(i));
                }
            }
            if (Directory.Exists(dirname))
            {
                Directory.Delete(dirname, true);
            }
        }

        private void dataGrid_UserDeletingRow(object sender, DataGridViewRowCancelEventArgs e)
        {
            e.Cancel = true;
        }

        private void menuDelete_Click(object sender, EventArgs e)
        {
            DataGridViewRow row = dataGrid.CurrentRow;
            int index = row.Index;
            string name = row.Cells[0].Value.ToString();

            if (MessageBox.Show("Da li želite da obrišete klijenta?\n   - " + name, "Brisanje klijenta",MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                dataGrid.Rows.Remove(row);
                rmDir(DATADIR + DIR_DELIMITER + toDir(name));
                menuSave.Enabled = true;
                saved = false;
                editingInProgressTitle();
            }
        }

        private void dataGrid_UserAddedRow(object sender, DataGridViewRowEventArgs e)
        {
            menuSave.Enabled = true;
            saved = false;
            editingInProgressTitle();
        }

        private void dataGrid_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
        {
            menuSave.Enabled = true;
            saved = false;
            editingInProgressTitle();
        }

        private void editingInProgressTitle()
        {
            if (!Regex.Match(Text, @"\*$").Success)
            {
                Text += " *";
            }
        }
        public static void _editingInProgressTitle()
        {
            if (!Regex.Match(dlgDanikla.dlgD.Text, @"\*$").Success)
            {
                dlgDanikla.dlgD.Text += " *";
            }
        }

        private void lblMessage_Click(object sender, EventArgs e)
        {
            lblMessage.Visible = false;
        }

        private void dlgDanikla_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (!saved)
            {
                statusMessage("Prvo morate sačuvati izmene!", "error");
                e.Cancel = true;
            }
        }
    }
}